<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { SlideshowDto, TaskOrderDto } from '@/apis/__generated/model/dto'
import { api } from '@/utils/api-instance.ts'
import { useHomeStore } from '@/stores/home-store.ts'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import _ from 'lodash'
import TitleTip from '@/views/home/title-tip.vue'
import { Dictionaries } from '@/apis/__generated/model/enums/DictConstants.ts'
import type { TaskType } from '@/apis/__generated/model/enums'
const homeStore = useHomeStore()
const orderList = ref<TaskOrderDto['TaskOrderRepository/COMPLEX_FETCHER_FOR_FRONT'][]>([])
const slideShowList = ref<SlideshowDto['SlideshowRepository/COMPLEX_FETCHER_FOR_FRONT'][]>([])
const lineChartRef = ref<HTMLElement>()
const pieChartRef = ref<HTMLElement>()

onMounted(async () => {
  slideShowList.value = (
    await api.slideshowForFrontController.query({
      body: {
        sorts: [
          {
            property: 'sort',
            direction: 'ASC',
          },
        ],
        pageSize: 20,
        query: { valid: true },
      },
    })
  ).content
  orderList.value = (
    await api.taskOrderForAdminController.query({
      body: { pageNum: 1, pageSize: 10000, query: {} },
    })
  ).content.map((row) => {
    row.createdTime = dayjs(row.createdTime).format('YYYY-MM-DD')
    return row
  })

  const times = new Set(
    orderList.value
      .map((row) => dayjs(row.createdTime))
      .sort((a, b) => a.diff(b, 'D'))
      .map((row) => dayjs(row).format('YYYY-MM-DD')),
  )
  const totalGroup = _.groupBy(orderList.value, (row) => row.createdTime)
  const payGroup = _.groupBy(
    orderList.value.filter((row) => row.baseOrder.payment.payTime),
    (row) => row.createdTime,
  )
  const chart = echarts.init(lineChartRef.value)
  chart.setOption({
    legend: {},
    tooltip: {},
    dataset: {},
    xAxis: {
      type: 'category',
      data: [...times],
    },
    yAxis: [
      {
        type: 'value',
      },
    ],
    series: [
      { type: 'line', name: '总订单数', data: [...times].map((row) => totalGroup[row].length) },
      {
        type: 'line',
        name: '支付订单数',
        data: [...times].map((row) => (payGroup[row] ? payGroup[row].length : 0)),
      },
    ],
  })
  const chart2 = echarts.init(pieChartRef.value)
  const typeGroup = _.groupBy(orderList.value, (row) => row.type)
  console.log(typeGroup)
  chart2.setOption({
    tooltip: {
      trigger: 'item',
    },
    legend: {
      top: '5%',
      left: 'center',
    },
    series: [
      {
        name: '订单类型分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          ...Object.keys(typeGroup).map((type) => {
            return {
              value: typeGroup[type].length,
              name: Dictionaries.TaskType[type as TaskType].keyName,
            }
          }),
        ],
      },
    ],
  })
})
</script>

<template>
  <div class="home-view">
    <div class="carousel">
      <el-carousel height="300px" motion-blur>
        <el-carousel-item
          class="carousel-item"
          v-for="(item, index) in slideShowList"
          :key="item.id"
        >
          <el-image
            preview-teleported
            class="slideshow"
            :src="item.picture"
            fit="contain"
            :initial-index="index"
            :preview-src-list="slideShowList.map((row) => row.picture)"
          ></el-image>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="order-history-chart" v-if="homeStore.checkRole(['管理员'])">
      <title-tip title="历史订单"> </title-tip>
      <div ref="lineChartRef" class="chart"></div>
    </div>
    <div class="order-history-chart" v-if="homeStore.checkRole(['管理员'])">
      <title-tip title="订单分布"> </title-tip>
      <div ref="pieChartRef" class="chart"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.home-view {
  .carousel {
    background-color: white;
    margin-bottom: 10px;
    overflow: hidden;
    border-radius: 5px;

    .slideshow {
      height: 100%;
      width: 100%;
    }
  }
  .chart {
    width: 100%;
    height: 500px;
  }
  .order-history-chart {
    background-color: white;
    padding: 15px;
    border-radius: 5px;
  }
}
</style>
